﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using Valentia.Kinection.DataTypes;
using Valentia.Kinection.Configuration;

namespace Valentia.Kinection.Configuration.Manager
{
    /// <summary>
    /// User control used to add/update utility user
    /// </summary>
    public partial class UtilityUserControl : UserControl
    {
        #region Declarations

        /// <summary>
        ///  Utility user ID
        /// </summary>
        private int utilityID = -1;

        /// <summary>
        /// Utility user login name
        /// </summary>
        private String utilityLoginName = string.Empty;

        #endregion

        #region Constructor

        /// <summary>
        /// Constructor
        /// </summary>
        public UtilityUserControl()
        {
            InitializeComponent();

            this.clbNotifications.Items.AddRange(Enum.GetNames(typeof(NotificationType)));

            this.clbNotifications.Items.Remove("No");
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Set the form control values with the provided utility user info.
        /// </summary>
        /// <param name="utilityUser"></param>
        public void InitializeWithUtilityUserData(UtilityUser utilityUser)
        {
            this.utilityID = utilityUser.ID;

            this.utilityLoginName = utilityUser.Login;

            txtUtilityName.Text = utilityUser.Name;
            txtLoginName.Text = utilityUser.Login;
            txtPassword.Text = utilityUser.Password;
            chkActive.Checked = utilityUser.Active;

            txtUtilityName.ReadOnly = true;
            txtLoginName.ReadOnly = true;

            List<UtilityUserAllowedNotification> utilityUserNotifications =
                ConfigurationHelper.GetUtilityUserNotificationsByUtilityUserID(utilityUser.ID);

            foreach (UtilityUserAllowedNotification notificationInfo in utilityUserNotifications)
            {
                this.clbNotifications.SetItemChecked(this.clbNotifications.Items.IndexOf(notificationInfo.NotificationTypeEnm.ToString()), true);
            }

            btnSaveUpdate.Text = "   Update";
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Validates the utility user data to be saved
        /// </summary>
        /// <returns>True/False : utility user data is valid</returns>
        private bool IsValidData()
        {
            errProvider.Clear();
            if (txtUtilityName.Text.Trim().Equals(string.Empty))
            {
                errProvider.SetError(txtUtilityName, "Please provide utility name");
                txtUtilityName.Focus();
                return false;
            }

            if (!Regex.Match(txtUtilityName.Text, "^[a-zA-Z0-9 ]+$").Success)
            {
                errProvider.SetError(txtUtilityName, "Utility name must be alphanumeric");
                txtUtilityName.Focus();
                return false;
            }

            if (txtLoginName.Text.Trim().Length == 0)
            {
                errProvider.SetError(txtLoginName, "Please provide login name");
                txtLoginName.Focus();
                return false;
            }

            if (!Regex.Match(txtLoginName.Text, "^[a-zA-Z0-9 ]+$").Success)
            {
                errProvider.SetError(txtLoginName, "Login name must be alphanumeric");
                txtLoginName.Focus();
                return false;
            }

            if (txtPassword.Text.Trim().Length == 0)
            {
                errProvider.SetError(txtPassword, "Please provide password");
                txtPassword.Focus();
                return false;
            }

            if (txtPassword.Text.IndexOf(" ", 0) != -1)
            {
                errProvider.SetError(txtPassword, "Space is not allowed in password");
                txtPassword.Focus();
                return false;
            }

            return true;
        }

        #endregion

        #region Form control events

        /// <summary>
        /// Occurs when Save/Update button is clicked
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">Event Args</param>
        private void btnSaveUpdate_Click(object sender, EventArgs e)
        {
            if (IsValidData())
            {

                if (this.utilityLoginName.Equals(string.Empty))
                {
                    if (ConfigurationHelper.GetUtilitiyUserByLoginName(txtLoginName.Text.Trim()) != null)
                    {
                        errProvider.SetError(txtLoginName, "Login name already exists");
                        txtLoginName.Focus();
                        return;
                    }

                    utilityID = ConfigurationHelper.SaveUtilityUser(txtUtilityName.Text.Trim()
                          , txtLoginName.Text.Trim(), txtPassword.Text, chkActive.Checked).ID;
                }
                else
                {
                    using (ConfigDatabaseEntities context = ConfigurationHelper.GetContext())
                    {
                        UtilityUser utilityUser = ConfigurationHelper.GetUtilitiyUserByLoginName(context, this.utilityLoginName);

                        if (utilityUser != null)
                        {
                            utilityUser.Name = txtUtilityName.Text.Trim();
                            utilityUser.Login = txtLoginName.Text.Trim();
                            utilityUser.Password = txtPassword.Text;
                            utilityUser.Active = chkActive.Checked;

                            context.SaveChanges();
                        }
                    }

                    ConfigurationHelper.DeleteUtilityUserNotificationsByUtilityUserID(this.utilityID);
                }



                foreach (object itemChecked in clbNotifications.CheckedItems)
                {
                    ConfigurationHelper.SaveUtilityUserNotification(utilityID
                        , (int)(NotificationType)(Enum.Parse(typeof(NotificationType), itemChecked.ToString(), true)));
                }

                ((Form)(this.Parent)).Close();
            }
        }

        /// <summary>
        /// Occurs when Cancel button is clicked
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">Event Args</param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            ((Form)(this.Parent)).Close();
        }

        /// <summary>
        /// Occurs when select all check box checked status change
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">Event Args</param>
        private void chkSelectAll_CheckedChanged(object sender, EventArgs e)
        {
            if (chkSelectAll.Checked)
            {
                for (int i = 0; i < clbNotifications.Items.Count; i++)
                {
                    clbNotifications.SetItemChecked(i, true);
                }
            }
            else
            {
                for (int i = 0; i < clbNotifications.Items.Count; i++)
                {
                    clbNotifications.SetItemChecked(i, false);
                }
            }
        }

        #endregion
    }
}
